package com.ruoyi.patrol.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.PatrolConstans;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.patrol.domain.PtGuard;
import com.ruoyi.patrol.domain.PtStaff;
import com.ruoyi.patrol.service.IPtGuardService;
import com.ruoyi.system.service.ISysUserService;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.runtime.TaskRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 安保人员Controller
 *
 * @author lkm
 * @date 2022-11-09
 */
@RestController
@RequestMapping("/patrol/guard")
public class PtGuardController extends BaseController {
    @Autowired
    private IPtGuardService ptGuardService;

    @Autowired
    private TaskRuntime taskRuntime;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询安保人员列表
     *
     * @PreAuthorize("@ss.hasPermi('patrol:guard:list')")
     */
    @GetMapping("/list")
    public TableDataInfo list(PtGuard ptGuard) {
        if (ptGuard.getSchoolId() == null) {
            ptGuard.setSchoolId(SecurityUtils.getSchoolId());
        }
//        List<PtGuard> list = getPtGuardsWithTask(ptGuard, false);
        startPage();
        List<PtGuard> list = ptGuardService.selectPtGuardList(ptGuard);
        return getDataTable(list);
    }

    /**
     * 查询代办任务
     */
    @PreAuthorize("@ss.hasPermi('patrol:guard:check:list')")
    @GetMapping("/check/list")
    public TableDataInfo checkList(PtGuard ptGuard) {
//        List<PtGuard> list = getPtGuardsWithTask(ptGuard, true);
        startPage();
        List<PtGuard> list = ptGuardService.selectPtGuardList(ptGuard);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('patrol:guard:check:list')")
    @GetMapping("/nocheck/list")
    public List<PtGuard> nocheckList() {
        List<PtGuard> list = ptGuardService.selectPtGuardNoCheckList();
        return list;
    }

    @PreAuthorize("@ss.hasPermi('patrol:guard:list')")
    @GetMapping("/nosubmit/list")
    public List<PtGuard> nosubmitList() {
        List<PtGuard> list = ptGuardService.selectPtGuardNoSubmitList(SecurityUtils.getSchoolId());
        return list;
    }

    /**
     * 导出安保人员列表
     */
    @PreAuthorize("@ss.hasPermi('patrol:guard:export')")
    @Log(title = "安保人员", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PtGuard ptGuard) {
        List<PtGuard> list = ptGuardService.selectPtGuardList(ptGuard);
        ExcelUtil<PtGuard> util = new ExcelUtil<PtGuard>(PtGuard.class);
        return util.exportExcel(list, "guard");
    }

    /**
     * 导入安保人员列表
     */
    @Log(title = "安保人员", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('patrol:guard:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<PtGuard> util = new ExcelUtil<PtGuard>(PtGuard.class);
        List<PtGuard> guardList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = ptGuardService.importGuard(guardList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 导入安保信息模板
     *
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<PtGuard> util = new ExcelUtil<PtGuard>(PtGuard.class);
        return util.importTemplateExcel("安保人员信息模板");
    }

    /**
     * 获取安保人员详细信息
     *
     * @PreAuthorize("@ss.hasPermi('patrol:guard:query')")
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(ptGuardService.selectPtGuardById(id));
    }

    /**
     * 获取保安数量
     *
     * @PreAuthorize("@ss.hasPermi('patrol:guard:query')")
     */
    @GetMapping(value = "/count")
    public AjaxResult getGuardCount() {
        AjaxResult ajax = AjaxResult.success();
        Long schoolId = SecurityUtils.getSchoolId();
        ajax.put("guardCount", ptGuardService.selectGuardCount(schoolId));
        return ajax;
    }

    /**
     * 新增安保人员
     */
    @PreAuthorize("@ss.hasPermi('patrol:guard:add')")
    @Log(title = "安保人员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PtGuard ptGuard) {
        if (PatrolConstans.NOT_UNIQUE.equals(ptGuardService.checkPhoneUnique(ptGuard))) {
            return AjaxResult.error("新增保安'" + ptGuard.getGuardName() + "'失败，手机号码已存在");
        }
        if (PatrolConstans.NOT_UNIQUE.equals(ptGuardService.checkIdcardUnique(ptGuard))) {
            return AjaxResult.error("新增保安'" + ptGuard.getGuardName() + "'失败，身份证号码已存在");
        }
        if (PatrolConstans.NOT_UNIQUE.equals(userService.checkUserNameUnique(ptGuard.getGuardPhonenumber()))) {
            return AjaxResult.error("新增安保人员'" + ptGuard.getGuardName() + "'失败，手机号码已存在");
        }
        return toAjax(ptGuardService.insertPtGuard(ptGuard));
    }

    /**
     * 修改安保人员
     */
    @PreAuthorize("@ss.hasPermi('patrol:guard:edit')")
    @Log(title = "安保人员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PtGuard ptGuard) {
        if (PatrolConstans.NOT_UNIQUE.equals(ptGuardService.checkPhoneUnique(ptGuard))) {
            return AjaxResult.error("修改安保人员'" + ptGuard.getGuardName() + "'失败，手机号码已存在");
        }
        if (PatrolConstans.NOT_UNIQUE.equals(ptGuardService.checkIdcardUnique(ptGuard))) {
            return AjaxResult.error("修改安保人员'" + ptGuard.getGuardName() + "'失败，身份证号码已存在");
        }

//        if (PatrolConstans.NOT_UNIQUE.equals(userService.checkUserNameUnique(ptGuard.getGuardPhonenumber()))) {
//            return AjaxResult.error("修改安保人员'" + ptGuard.getGuardName() + "'失败，手机号码已存在");
//        }
        return toAjax(ptGuardService.updatePtGuard(ptGuard));
    }

    /**
     * 提交安保人员
     */
    @PreAuthorize("@ss.hasPermi('patrol:guard:edit')")
    @Log(title = "安保人员", businessType = BusinessType.UPDATE)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody PtGuard ptGuard) {
        return toAjax(ptGuardService.submitPtGuard(ptGuard));
    }

    /**
     * 审核安保人员
     */
    @PreAuthorize("@ss.hasPermi('patrol:guard:check')")
    @Log(title = "安保人员", businessType = BusinessType.UPDATE)
    @PostMapping("/check")
    public AjaxResult check(@RequestBody PtGuard ptGuard) {
        return toAjax(ptGuardService.checkGuard(ptGuard));
    }

    /**
     * 删除安保人员
     */
    @PreAuthorize("@ss.hasPermi('patrol:guard:remove')")
    @Log(title = "安保人员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        if (ptGuardService.isGuardOnSchedule(ids[0])) {
            return AjaxResult.error("该人员有未完成的巡查，暂不能删除！");
        }
        return toAjax(ptGuardService.deletePtGuardByIds(ids));
    }

    /**
     * 得到保安列表，同时包含task对象
     *
     * @param ptGuard
     * @return
     */
    private List<PtGuard> getPtGuardsWithTask(PtGuard ptGuard, Boolean isCheck) {
        List<PtGuard> list = null;
        if (!isCheck) {
            startPage();
            list = ptGuardService.selectPtGuardList(ptGuard);
        } else {
            startPage();
            list = ptGuardService.selectPtGuardCheckList(ptGuard);
        }
        Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, Integer.MAX_VALUE));
        if (tasks != null && tasks.getTotalItems() > 0) {
            for (PtGuard guard : list) {
                for (Task task : tasks.getContent()) {
                    if (task.getProcessInstanceId().equals(guard.getInstanceId())) {
                        guard.setTask(task);
                        break;
                    }
                }
            }
        }
        return list;
    }

    //    @PreAuthorize("@ss.hasPermi('patrol:guard:list')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect(PtGuard ptGuard) {
        ptGuard.setSchoolId(SecurityUtils.getSchoolId());
        //ptGuard.setStatus(PatrolConstans.GUARD_PASS);
        List<PtGuard> list = ptGuardService.selectPtGuardList(ptGuard);
        return AjaxResult.success(list);
    }
}
